package org.lcogt.tools.fitsviewer.server;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContext;

import nom.tam.fits.Fits;
import nom.tam.fits.FitsException;
import nom.tam.fits.Header;
import nom.tam.fits.ImageHDU;
import nom.tam.util.Cursor;

import org.lcogt.tools.fitsviewer.client.FitsIDService;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class FitsIDServiceImpl extends RemoteServiceServlet implements FitsIDService {
	Fits fits;
	ImageHDU imageHDU;
	String basePath;
	String currentPath;
	Properties prop;
	@Override
	public String[] getFitsID(String fileName) {
		//Finds path on server
		if(prop == null)
		{
			prop = new Properties();
			ServletContext context = getServletContext();
			InputStream is = context.getResourceAsStream("FitsViewer.properties");
			try {
				prop.load(is);
				basePath = prop.getProperty("serverPathOfFitsFiles");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		String[] results= new String[6];
			try {
				//trys to load fits file
				fits = new Fits(new File(basePath+fileName));
			} catch (FitsException e) {
				e.printStackTrace();
			}
			try{
				//trys to get elements about the fits file that coorespond to the ones in the database
				//Will still work for images that are not in the database
				imageHDU = (ImageHDU) fits.readHDU();
				Header header = imageHDU.getHeader();
				results[0]= header.getStringValue("TAGID");
				results[1]= header.getStringValue("PROPID");
				results[2]= header.getStringValue("GROUPID");
				results[3]= header.getStringValue("OBSID");
				results[4]= header.getStringValue("USERID");
				results[5]= header.getStringValue("OBJECT");
			} catch (Exception e){
				e.printStackTrace();
			}
			return results;
	}

}
